package main

import(
    "github.com/elazarl/go-bindata-assetfs"
    "net/http"
    "path"
    "strings"
    "context"
    "fmt"

    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "google.golang.org/grpc"
    swagger "grpc-test/swagger-ui"
    gw "grpc-test/pb"
)

//注册转发功能，外部的RESTful请求转发到server.go的功能
func newGateway(ctx context.Context)(http.Handler,error){

    //返回一个拨号选项，该选项禁用此 ClientConn 的传输安全性。
    opts := []grpc.DialOption{grpc.WithInsecure()}

    //注册网关转发路由服务
    gwmux := runtime.NewServeMux()
    if err:= gw.RegisterHelloSVCHandlerFromEndpoint(ctx, gwmux,":50051",opts); err != nil{
        return nil,err
    }
    return gwmux,nil

}

//配置读取swagger的json文件
func serveSwaggerFile(w http.ResponseWriter, r *http.Request){
    fmt.Println("start serveSwaggerFile")

    if !strings.HasSuffix(r.URL.Path,"swagger.json"){
        fmt.Println("Not Found:",r.URL.Path)
        http.NotFound(w,r)
        return
    }

    p := strings.TrimPrefix(r.URL.Path, "/swagger/")
    p = path.Join("pb/protos/",p)

    fmt.Println("serving swagger file",p)
    http.ServeFile(w,r,p)
}

//配置ui路由
func serveSwaggerUI(mux *http.ServeMux){
    fileServer:= http.FileServer(&assetfs.AssetFS{
        Asset: swagger.Asset,
        AssetDir: swagger.AssetDir,
        Prefix: "swagger-ui/dist",
    })
    prefix := "/swagger-ui/"
    mux.Handle(prefix,http.StripPrefix(prefix,fileServer))

}

//启动入口
func run() error{
    //创建一个新协程，退出时关闭
    ctx := context.Background()
    ctx,cancel := context.WithCancel(ctx)
    defer cancel()

    gwmux,err := newGateway(ctx)
    if err!= nil{
        panic(err)
    }

    //注册路由
    mux := http.NewServeMux()
    mux.Handle("/", gwmux)
    mux.HandleFunc("/swagger/",serveSwaggerFile)
    serveSwaggerUI(mux)

    fmt.Println("grpc-gateway listen on localhost:9090")
    return http.ListenAndServe(":9090",mux)
}


func main(){
    
    if err:= run();err != nil{
        fmt.Println("err:",err)
        panic(err)
    }
}
